package com.zlp.controller;

import com.zlp.oauth.constant.AuthConstant;
import com.zlp.oauth.dto.Oauth2TokenResp;
import com.zlp.utils.api.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.util.Arrays;
import java.util.Map;

/**
 * 自定义Oauth2获取令牌接口
 * Created by macro on 2020/7/17.
 */
@Controller
@RequestMapping("/oauth")
@Api(value = "oauth", tags = "认证中心登录认证")
public class AuthController {

    @Resource
    private TokenEndpoint tokenEndpoint;

    @Resource
    private  ClientDetailsService clientDetailsService;

    @ApiOperation("Oauth2获取token")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "grant_type", value = "授权模式", required = true),
            @ApiImplicitParam(name = "client_id", value = "Oauth2客户端ID", required = true),
            @ApiImplicitParam(name = "client_secret", value = "Oauth2客户端秘钥", required = true),
            @ApiImplicitParam(name = "refresh_token", value = "刷新token"),
            @ApiImplicitParam(name = "username", value = "登录用户名"),
            @ApiImplicitParam(name = "scope", value = "作用域"),
            @ApiImplicitParam(name = "password", value = "登录密码")
    })
    @ResponseBody
    @PostMapping(value = "/token22")
    public Result<Oauth2TokenResp> postAccessToken(@ApiIgnore Principal principal,
                                                   @ApiIgnore @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {

        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        Oauth2TokenResp oauth2TokenDto = Oauth2TokenResp.builder()
                .token(oAuth2AccessToken.getValue())
                .refreshToken(oAuth2AccessToken.getRefreshToken().getValue())
                .expiresIn(oAuth2AccessToken.getExpiresIn())
                .tokenHead(AuthConstant.JWT_TOKEN_PREFIX).build();

        return Result.success(oauth2TokenDto);
    }

    /**
     * 认证页面
     *
     * @param modelAndView
     * @return ModelAndView
     */
    @GetMapping("/showLogin")
    public ModelAndView require(ModelAndView modelAndView) {
        modelAndView.setViewName("/ftl/login");
        return modelAndView;
    }

    /**
     * 确认授权页面
     *
     * @param request
     * @param session
     * @param modelAndView
     * @return
     */
    @GetMapping("/confirm_access_bak")
    public ModelAndView confirm(HttpServletRequest request, HttpSession session, ModelAndView modelAndView) {

        String scope = request.getParameter("scope");
        modelAndView.addObject("scopeList", Arrays.asList(scope));

        Object auth = session.getAttribute("authorizationRequest");
        if (auth != null) {
            AuthorizationRequest authorizationRequest = (AuthorizationRequest) auth;
            ClientDetails clientDetails = clientDetailsService.loadClientByClientId(authorizationRequest.getClientId());
            modelAndView.addObject("app", clientDetails.getAdditionalInformation());
			modelAndView.addObject("clientId", clientDetails.getClientId());
        }

        modelAndView.setViewName("ftl/confirm");
        return modelAndView;
    }


}
